package com.springboot02amqp.amqp;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

@SpringBootTest
public class ProducerDemo {

    @Test
    public void Producer() throws IOException, TimeoutException {
        //创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");

        //通过连接工厂创建连接
        Connection connection = factory.newConnection();

       //通过连接创建一个Channel
        Channel channel = connection.createChannel();

        //声明一个交换机,参数1：交换机名称,参数2：交换机类型，fanout、topic、direct、headers, 参数3：是否持久化, 参数4：是否自动删除, 参数5：其他参数
       channel.exchangeDeclare("test_exchange", "direct", true, false, null);

        //声明一个队列,参数1：队列名称,参数2：是否持久化,参数3：是否独占,参数4：是否自动删除,参数5：其他参数
        channel.queueDeclare("test_queue", true, false, false, null);

        //绑定交换机和队列,参数1：队列名称,参数2：交换机名称,参数3：路由key
        channel.queueBind("test_queue", "test_exchange", "test_queue");

        //发送消息,参数1：交换机名称,参数2：路由key,参数3：其他参数,参数4：消息内容
        channel.basicPublish("test_exchange", "test_queue", null, "hello rabbitmq".getBytes());

        //关闭通道
        channel.close();

        //关闭连接
        connection.close();

        System.out.println("创建producer成功");
    }

}